<template>
  <div class="container">
    <div class="nav">
      <div
        v-for="state in orderStateEnums"
        :key="state.value"
        :class="{ activeOrderStateView: state.value === page.orderState }"
        @click="changeOrderListView(state.value)"
      >
        <span>{{ state.name }}{{ listData.stateCountMap[state.value] ? ` (${listData.stateCountMap[state.value]})` : '' }}</span>
      </div>
    </div>
    <div class="body">
      <div class="control">
        <view class="input-box">
          <el-form-item label="订单号">
            <el-input v-model="page.orderNo" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="page.phone" />
          </el-form-item>
          <el-form-item label="下单时间">
            <el-date-picker
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY/MM/DD ddd"
              time-format="A hh:mm:ss"
              v-model="datePickerValue"
            />
          </el-form-item>
        </view>
        <view class="btn-box">
          <el-button type="primary" @click="refreshList">查询</el-button>
          <el-button type="primary" @click="resetPageParamsAndRefresh">重置</el-button>
        </view>
      </div>
      <view class="list">
        <el-table stripe style="width: 100%" :data="listData.list">
          <el-table-column prop="orderNo" label="订单号" />
          <el-table-column prop="code" label="取餐号" v-if="page.orderState === OrderState.PRODUCTION_COMPLETED">
            <template v-slot="scope">
              {{ scope.row.code ?? '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="isImmediate" label="是否立即单">
            <template v-slot="scope">
              <span v-if="scope.row.designatedDeliveryTime == null"><SvgIcon name="fast" color="#606266" size="13px"></SvgIcon>是</span>
              <span v-else><SvgIcon name="reservation" size="13px"></SvgIcon>否</span>
            </template>
          </el-table-column>
          <el-table-column prop="dishSummary" label="菜品概要" width="180" />
          <el-table-column prop="remark" label="备注信息" />
          <el-table-column prop="amount" label="订单金额" />
          <el-table-column
            prop="cancelReason"
            label="取消原因"
            v-if="page.orderState === OrderState.APPLY_FOR_AFTER_SALE || page.orderState === OrderState.ORDER_CANCELED"
          >
            <template v-slot="scope">
              <span v-if="scope.row.rejectionReason != null">商家拒单: {{ scope.row.rejectionReason }}</span>
              <span v-else>{{ scope.row.cancelReason }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="estimatedDeliveryTime" label="送达时间" width="100" />
          <el-table-column prop="consigneeName" label="收货人" />
          <el-table-column prop="consigneePhone" label="手机号" width="120" />
          <el-table-column prop="receivingMethodName" label="收货方式" />
          <el-table-column prop="address" label="收货地址" width="100" />
          <el-table-column fixed="right" label="操作" width="100">
            <template v-slot="scope">
              <view class="operation">
                <template v-if="page.orderState === OrderState.WAITING_FOR_ACCEPTANCE">
                  <el-button size="small" @click="receivingOrder(scope.row.id)">接单</el-button>
                  <el-button type="danger" size="small" @click="shopRejectOrderDialogRef.callOut(scope.row.id)">拒单</el-button>
                </template>
                <template v-if="page.orderState === OrderState.ORDER_ACCEPTED">
                  <el-button size="small" v-if="scope.row.receivingMethod !== ReceivingMethodType.SHOP_EAT" @click="productionCompleted(scope.row.id)"
                    >制作完成</el-button
                  >
                  <el-button size="small" v-else @click="productionCompleted(scope.row.id)">已端餐</el-button>
                </template>
                <template v-if="page.orderState === OrderState.PRODUCTION_COMPLETED">
                  <el-button size="small" v-if="scope.row.receivingMethod === ReceivingMethodType.SELF_PICKUP">已自提</el-button>
                </template>
                <template v-if="page.orderState === OrderState.PRODUCTION_COMPLETED">
                  <el-button size="small" v-if="scope.row.receivingMethod === ReceivingMethodType.SELF_PICKUP">已取餐</el-button>
                </template>
                <template v-if="page.orderState === OrderState.APPLY_FOR_AFTER_SALE">
                  <el-button size="small">同意</el-button>
                </template>
                <el-button type="primary" size="small">查看</el-button>
              </view>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="paging-component"
          background
          layout="prev, pager, next"
          :total="listData.totalPage"
          v-model:current-page="page.currentPage"
          :page-size="page.pageSize"
          @prev-click="pageChange(page.currentPage - 1)"
          @next-click="pageChange(page.currentPage + 1)"
          @current-change="pageChange"
        />
      </view>
    </div>
    <shop-reject-order-dialog ref="shopRejectOrderDialogRef" @rejected="refreshList" />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, getCurrentInstance, watch } from 'vue'
import ComponentHat from '@/plugins/type'
const { $store, $API, $modal } = <ComponentHat>getCurrentInstance().proxy

import { ShopOrderPageParam } from '@/types/param/order'
import { ShopOrderPage } from '@/types/response/order'
import { ReceivingMethodType } from '@/enums/ReceivingMethodType'
import ShopRejectOrderDialog from './components/shop-reject-order-dialog/index.vue'
import OrderState from '@/enums/OrderState'

const orderStateEnums = ref([
  { name: '全部订单', value: null },
  { name: '待接单', value: 2 },
  { name: '已接单', value: 3 },
  { name: '待取餐', value: 4 },
  { name: '派送中', value: 5 },
  { name: '已完成', value: 6 },
  { name: '申请退单', value: 7 },
  { name: '已取消', value: 8 }
])
// shopRejectOrderDialogRef
const shopRejectOrderDialogRef = ref()

// 分页条件参数
const page = ref<ShopOrderPageParam>(new ShopOrderPageParam())
// 查询范围
const datePickerValue = ref()
watch(
  () => datePickerValue.value,
  (value) => {
    page.value.startTime = value != null ? value[0] : null
    page.value.endTime = value != null ? value[1] : null
  }
)
const listData = ref<ShopOrderPage>(new ShopOrderPage())

// 刷新列表
async function refreshList() {
  const copySelectParams = JSON.parse(JSON.stringify(page.value))
  // 其实后端传过来的是字符串，需要转为对象，在发出请求时会将Date对象转为后端统一需要的时间格式
  if (copySelectParams.startTime != null) copySelectParams.startTime = new Date(copySelectParams.startTime)
  if (copySelectParams.endTime != null) copySelectParams.endTime = new Date(copySelectParams.endTime)
  // 格式化前端需要的
  const result = await $API.order.selectShopOrderList(copySelectParams)
  if (result.success) {
    listData.value = result.data
    console.log('listData.value=', listData.value)
  }
}
// 重置参数
function resetPageParamsAndRefresh() {
  // 不重置orderState
  const orderState = page.value.orderState
  page.value = new ShopOrderPageParam()
  datePickerValue.value = null
  page.value.currentPage = 1
  page.value.pageSize = 15
  // 恢复orderState
  page.value.orderState = orderState
  refreshList()
}
// 查询的订单类型改变
function changeOrderListView(newStateValue: number) {
  page.value.orderState = newStateValue

  refreshList()
}
// 页数改变
function pageChange(newPage: number) {
  page.value.currentPage = newPage
  if (page.value.currentPage - 1 < 0) {
    page.value.currentPage = 0
  }
  if (page.value.currentPage + 1 > listData.value.totalPage) {
    page.value.currentPage = listData.value.totalPage
  }
  refreshList()
}
// 监听事件
$store.notice.notice.on((data) => {
  console.log('监听到有事件')
  refreshList()
})
// 接单
let count = 0
function refreshFunFactory() {
  let timer: null | number = null
  return function () {
    if (timer != null) {
      clearTimeout(timer)
      timer = null
    }
    timer = setTimeout(() => {
      count = 0
    }, 3000)
  }
}
const refreshCount = refreshFunFactory()
async function receivingOrder(orderId: number) {
  const result = await $API.order.shopReceivingOrder(orderId)
  if (result.success) {
    $modal.msgSuccess(`接单成功 x${++count}`)
    refreshCount()
    refreshList()
  } else {
    $modal.alertError(result.message)
  }
}
// 制作完成/已端餐
async function productionCompleted(orderId: number) {
  const result = await $API.order.productionCompleted(orderId)
  if (!result.success) {
    $modal.msgError(result.message)
  } else {
    $modal.msgSuccess('操作成功！')
    refreshList()
  }
}
onMounted(() => {
  resetPageParamsAndRefresh()
})
</script>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  height: 100%;

  .nav {
    display: flex;
    padding: 10px;
    width: 100%;
    box-sizing: border-box;

    > div {
      margin: 0 1px;
      cursor: pointer;

      > span {
        display: inline-block;
        padding: 0 30px;
        font-size: 13px;
        background-color: #fff;
        line-height: 37px;
      }
    }

    .activeOrderStateView {
      color: #ffc524;
    }
  }

  .body {
    position: relative;
    display: flex;
    padding: 10px;
    width: 100%;
    background-color: #fff;
    flex-grow: 1;
    box-sizing: border-box;
    flex-direction: column;

    .control {
      display: flex;
      justify-content: space-between;

      .input-box {
        display: flex;
        width: 0;
        flex-grow: 1;

        > * {
          margin-right: 20px;
        }
      }
    }

    .list::-webkit-scrollbar {
      display: none; /* Chrome Safari */
    }

    .list {
      flex-grow: 1;
      flex-shrink: 0;
      overflow-y: auto;
      height: 0;

      .operation {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        > * {
          margin: 0;
          margin: 2px;
        }
      }

      .paging-component {
        margin: 15px auto;
      }
    }
  }
}
</style>
<style>
.el-form-item__label {
  font-size: 13px;
}
</style>
@/enums/ReceivingMethodType
